// 这里也是一种发布订阅
// new Queue()
// .task(1000,()=>console.log(1))
// .task(2000,()=>console.log(2))
// .task(3000,()=>console.log(3)).start();
// 实现一个Queue函数，调用start之后，1s后打印1，接着2s后打印2，然后3s后打印3
class Queue {
    constructor() {
        this.taskList = [];
    }
    task(delay, fn) {
        this.taskList.push(() => sleep(delay, fn))
        return this
    }
    start() {
        this.taskList.forEach(async (fn) => {
            await fn()
        })
    }
}

function sleep(delay, fn) {
    return new Promise((resolve, reject) => {
        setTimeout(() => {
            resolve(fn())
        }, delay)
    })
}

// new Queue()
//     .task(1000, () => console.log(1))
//     .task(2000, () => console.log(2))
//     .task(3000, () => console.log(3)).start();


// 变种 lazyMan
// LazyMan('Tony').eat('lunch').eat('dinner').sleepFirst(5).sleep(10).eat('junk food');
// Hi I am Tony
// 等待了5秒...
// I am eating lunch
// I am eating dinner
// 等待了10秒...
// I am eating junk food
class lazyManClass {
    constructor(name) {
        this.name = name;
        this.taskList = [];
        console.log(`nihao woshi ${name}`)
        setTimeout(() => {
            this.next()
        }, 0)
    }

    eat(name) {
        let that = this
        let fn = function () {
            console.log(`I am eating ${name}`)
            that.next()
        }
        this.taskList.push(fn)
        return this
    }

    // 保证最先执行
    sleepFirst(time) {
        let that = this
        let fn = function () {
            setTimeout(() => {
                console.log(`等待了${time}秒...`)
                that.next()
            }, time*1000)
        }
        this.taskList.unshift(fn)
        return this

    }

    sleep(time) {
        let that = this;
        let fn = function () {
            setTimeout(() => {
                console.log(`等待了${time}秒...`)
                that.next()
            }, time*1000)
        }
        this.taskList.push(fn)
        return this
    }
    next() {
        var fn = this.taskList.shift()
        fn && fn()
    }
}

function LazyMan(name) {
    return new lazyManClass(name)
}

LazyMan('Tony').eat('lunch').eat('dinner').sleepFirst(5).sleep(10).eat('junk food');